package com.roc.web.action.excel;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.bean.MerinfoSearchBean;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.OrgBean;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerchantStatus;
import com.roc.util.constant.Role;
import com.roc.web.action.merinfo.MerinfoChangeSearchCondition;
@Component
@Scope("prototype")
@Namespace("/merinfoBatchExport")
@SuppressWarnings("all")
public class MerinfoExcel extends PaginationBaseAction{
	static Logger logger=Logger.getLogger(MerinfoExcel.class);
	
	private InputStream excelFile;
	private String  excelName;
	private MerinfoSearchCondition searchCondition;
	private List<OrgBean> orgList=new ArrayList<OrgBean>();
	//private List<String> midList=new ArrayList<String>();
//	protected List<String> multi_sel_str;;
	
	
	@Autowired
	IExcelService excelService;
	@Autowired
	IPagenitionService pagenitionService;
	@Autowired
	IorgService orgService;
	@Autowired 
	IMerchantServices merchantServices;
	
	@Action(value = "initExport", results = { @Result(name = "success", location = "/pages/merinfo/merinfoBatchExport.jsp")
    })
	public String initExport() throws Exception{
		try{
			org();
		}catch (Exception e) {
		// TODO: handle exception
		addActionError("加载信息失败，请联系客服人员");
		logger.error(e.getMessage(),e);
		}
		return SUCCESS;
	}
	
	public void org() throws Exception{
		Operators loginOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		try {
			getRequest().setAttribute("areaList", ConfigProperties.getAreaCodeProperties());
			//初始化机构
			orgList=orgService.listOrgs(loginOperators);
			//初始化结算周期
			List<Object> objList=merchantServices.queryCycle();
			getRequest().setAttribute("cycList", objList);

		}catch (Exception e) {
			logger.error("商户信息查询初始化失败",e);
			throw new Exception("商户信息查询初始化失败");
		}
	}
	@Action(value = "queryMerinfoExport", 
			results = { @Result(name = "success", location = "/pages/merinfo/merinfoBatchExport.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryMerinfoExport() throws Exception{
		Operators loginOperators = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		
		if(searchCondition==null){
			searchCondition=(MerinfoSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new MerinfoSearchCondition();
			}
		}
		try {
			
			initExport();
			if(Role.AGENT.getCode().equals(loginOperators.getRoleType())){//代理商
				 List<Operators> opList=merchantServices.listAllSubMerchants(loginOperators.getId());
				 String[] agentList = new String[opList.size()];
				 for (int i=0;i<opList.size();i++) {
					 
					Operators o=opList.get(i);
					agentList[i]=Long.toString(o.getId());
					
				}
			   searchCondition.setAgentId(agentList);
			}
			if(Role.MERCHANT.getCode().equals(loginOperators.getRoleType())){//商户
				searchCondition.setMerchantNo(loginOperators.getAccountNo());
			}
			//searchCondition.setAgentId(loginOperators.getId());
			//this.setCurrentPage(this.checkCurrentPage());
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				
			}
			List<MerinfoSearchBean> msList=new ArrayList<MerinfoSearchBean>();
			dealWith(msList,searchRsList);
			/*if(searchRsList.size()>0 && searchRsList!=null){
				
				Iterator iterator=searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj= (Object[])iterator.next();
					MerinfoSearchBean  msb=new MerinfoSearchBean(); 
					msb.setMid(Constance.Null2EmptyTrim(obj[0]));
					msb.setMerName(Constance.Null2EmptyTrim(obj[1]));
					msb.setMerBrName(Constance.Null2EmptyTrim(obj[2]));
					msb.setMerKind(Constance.Null2EmptyTrim(obj[3]));
					msb.setFlag(MerchantStatus.valueOfCode(Integer.parseInt(obj[4].toString())).getName());
					msb.setRsvl(Constance.Null2EmptyTrim(obj[5]));
					msb.setRsvl3(Constance.Null2EmptyTrim(obj[6]));
					msb.setInterContact(Constance.Null2EmptyTrim(obj[7]));
					msb.setPerPhone(Constance.Null2EmptyTrim(obj[8]));
					msb.setPerName(Constance.Null2EmptyTrim(obj[9]));
					msb.setCycleId(Constance.Null2EmptyTrim(obj[10]));
					msb.setCatdType(Constance.Null2EmptyTrim(obj[11]));
					msb.setCardNo(Constance.Null2EmptyTrim(obj[12]));
					msb.setAddr(Constance.Null2EmptyTrim(obj[13]));
					msb.setAreaCode(Constance.Null2EmptyTrim(obj[14]));
					msb.setAgentId(Constance.Null2EmptyTrim(obj[15]));
					msb.setFlagCode(Constance.Null2EmptyTrim(obj[4].toString()));
					msb.setRate(Constance.Null2EmptyTrim(obj[16]));
					msb.setRateType(Constance.Null2EmptyTrim(obj[17]));
					msb.setAmt(Constance.Null2EmptyTrim(obj[18]));
					msb.setBus_lic(Constance.Null2EmptyTrim(obj[19]));
				
					msList.add(msb);
				}
			}*/
		//	dealWithTheListSpecially(searchRsList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, msList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		} catch (ServiceException e) {
			
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	
	@Action(value="batchExport",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/merinfo/merinfoBatchExport.jsp") }) 
	public String batchExport(){
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try{
			if(Role.AGENT.getCode().equals(op.getRoleType())){//代理商
				 List<Operators> opList=merchantServices.listAllSubMerchants(op.getId());
				 String[] agentList = new String[opList.size()];
				 for (int i=0;i<opList.size();i++) {
					 
					Operators o=opList.get(i);
					agentList[i]=Long.toString(o.getId());
					
				}
			   searchCondition.setAgentId(agentList);
			}
			if(Role.MERCHANT.getCode().equals(op.getRoleType())){//商户
				searchCondition.setMerchantNo(op.getAccountNo());
			}
			//searchCondition.setAgentId(op.getId());
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			List<MerinfoSearchBean> msList=new ArrayList<MerinfoSearchBean>();
			dealWith(msList,searchRsList);
			/*if(searchRsList.size()>0 && searchRsList!=null){
				
				Iterator iterator=searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj= (Object[])iterator.next();
					MerinfoSearchBean  msb=new MerinfoSearchBean(); 
					msb.setMid(Constance.Null2EmptyTrim(obj[0]));
					msb.setMerName(Constance.Null2EmptyTrim(obj[1]));
					msb.setMerBrName(Constance.Null2EmptyTrim(obj[2]));
					msb.setMerKind(Constance.Null2EmptyTrim(obj[3]));
					msb.setFlag(MerchantStatus.valueOfCode(Integer.parseInt(obj[4].toString())).getName());
					msb.setRsvl(Constance.Null2EmptyTrim(obj[5]));
					msb.setRsvl3(Constance.Null2EmptyTrim(obj[6]));
					msb.setInterContact(Constance.Null2EmptyTrim(obj[7]));
					msb.setPerPhone(Constance.Null2EmptyTrim(obj[8]));
					msb.setPerName(Constance.Null2EmptyTrim(obj[9]));
					msb.setCycleId(Constance.Null2EmptyTrim(obj[10]));
					msb.setCatdType(Constance.Null2EmptyTrim(obj[11]));
					msb.setCardNo(Constance.Null2EmptyTrim(obj[12]));
					msb.setAddr(Constance.Null2EmptyTrim(obj[13]));
					msb.setAreaCode(Constance.Null2EmptyTrim(obj[14]));
					msb.setAgentId(Constance.Null2EmptyTrim(obj[15]));
					msb.setFlagCode(Constance.Null2EmptyTrim(obj[4].toString()));
					msb.setRate(Constance.Null2EmptyTrim(obj[16]));
					msb.setRateType(Constance.Null2EmptyTrim(obj[17]));
					msb.setAmt(Constance.Null2EmptyTrim(obj[18]));
					msb.setBus_lic(Constance.Null2EmptyTrim(obj[19]));
					msb.setAmount1(Constance.Null2EmptyTrim(obj[20]));
					msb.setAmount2(Constance.Null2EmptyTrim(obj[20]));
					msb.setDayTotalAmt1(Constance.Null2EmptyTrim(obj[21]));
					msb.setDayTotalAmt2(Constance.Null2EmptyTrim(obj[22]));
					msb.setMonthTotalAmt1(Constance.Null2EmptyTrim(obj[23]));
					msb.setMonthTotalAmt2(Constance.Null2EmptyTrim(obj[24]));
				
					msList.add(msb);
				}
			}*/
			HSSFWorkbook work=excelService.merinfoTransQueryExcel(msList,op);
			 ByteArrayOutputStream output = new ByteArrayOutputStream();  
			         work.write(output);  
			   
			        byte[] ba = output.toByteArray();  
			         excelFile = new ByteArrayInputStream(ba);  
			         output.flush();  
			         output.close();  
		}catch(Exception e){
			logger.info("######导出Excel失败######");
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	@Action(value="someExport",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/merinfo/merinfoBatchExport.jsp") })
	public String someExport() {
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try{
			//initSomeDataForAction();
			List<String> midList=this.getMulti_sel_str();//(List<String>) getSession().getAttribute("multi_sel_str");//
			//List<String> mList=this.getMidList();
			//List s=(List) this.getRequest().getAttribute("midList");
			for(int i=0;i<midList.size();i++){
				String  mid=midList.get(i);
				searchCondition.setMerchantNo(mid);
				List<Object> object = pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), 1);
				searchRsList.addAll(object);		
			}
			List<MerinfoSearchBean> msList=new ArrayList<MerinfoSearchBean>();
			dealWith(msList,searchRsList);
			HSSFWorkbook work=excelService.merinfoTransQueryExcel(msList,op);
			 ByteArrayOutputStream output = new ByteArrayOutputStream();  
			         work.write(output);  
			   
			        byte[] ba = output.toByteArray();  
			         excelFile = new ByteArrayInputStream(ba);  
			         output.flush();  
			         output.close();  
		}catch(Exception e){
				logger.info("######导出Excel失败######");
				addActionError(e.getMessage());
				return ERROR;
		}
		return SUCCESS;
	}
	
	
	private List<MerinfoSearchBean> dealWith(List<MerinfoSearchBean> msList,List<Object> searchRsList){
		if(searchRsList.size()>0 && searchRsList!=null){
			
			Iterator iterator=searchRsList.iterator();
			while (iterator.hasNext()) {
				Object[] obj= (Object[])iterator.next();
				MerinfoSearchBean  msb=new MerinfoSearchBean(); 
				msb.setMid(Constance.Null2EmptyTrim(obj[0]));
				msb.setMerName(Constance.Null2EmptyTrim(obj[1]));
				msb.setMerBrName(Constance.Null2EmptyTrim(obj[2]));
				msb.setMerKind(Constance.Null2EmptyTrim(obj[3]));
				msb.setFlag(MerchantStatus.valueOfCode(Integer.parseInt(obj[4].toString())).getName());
				msb.setRsvl(Constance.Null2EmptyTrim(obj[5]));
				msb.setRsvl3(Constance.Null2EmptyTrim(obj[6]));
				msb.setInterContact(Constance.Null2EmptyTrim(obj[7]));
				msb.setPerPhone(Constance.Null2EmptyTrim(obj[8]));
				msb.setPerName(Constance.Null2EmptyTrim(obj[9]));
				msb.setCycleId(Constance.Null2EmptyTrim(obj[10]));
				msb.setCatdType(Constance.Null2EmptyTrim(obj[11]));
				msb.setCardNo(Constance.Null2EmptyTrim(obj[12]));
				msb.setAddr(Constance.Null2EmptyTrim(obj[13]));
				msb.setAreaCode(Constance.Null2EmptyTrim(obj[14]));
				msb.setAgentId(Constance.Null2EmptyTrim(obj[15]));
				msb.setFlagCode(Constance.Null2EmptyTrim(obj[4].toString()));
				msb.setRate(Constance.Null2EmptyTrim(obj[16]));
				msb.setRateType(Constance.Null2EmptyTrim(obj[17]));
				msb.setAmt(Constance.Null2EmptyTrim(obj[18]));
				msb.setBus_lic(Constance.Null2EmptyTrim(obj[19]));
				msb.setAmount1(Constance.Null2EmptyTrim(obj[20]));
				msb.setAmount2(Constance.Null2EmptyTrim(obj[21]));
				msb.setDayTotalAmt1(Constance.Null2EmptyTrim(obj[22]));
				msb.setDayTotalAmt2(Constance.Null2EmptyTrim(obj[23]));
				msb.setMonthTotalAmt1(Constance.Null2EmptyTrim(obj[24]));
				msb.setMonthTotalAmt2(Constance.Null2EmptyTrim(obj[25]));
				msb.setSetTime(Constance.Null2EmptyTrim(obj[26]));
				msb.setEngName(Constance.Null2EmptyTrim(obj[27]));
				msb.setEngBrName(Constance.Null2EmptyTrim(obj[28]));
				msb.setMcc(Constance.Null2EmptyTrim(obj[29]));
				//msb.setAgentId(Constance.Null2EmptyTrim(obj[30]));
				msb.setRealName(Constance.Null2EmptyTrim(obj[30]));
			    msb.setMerStatus(Constance.Null2EmptyTrim(obj[31]));
			    
				if( Constance.Null2EmptyTrim(msb.getMerStatus()).equals("A0")){
					msb.setMerStatus("正常");
				}else if(Constance.Null2EmptyTrim(msb.getMerStatus()).equals("A1")){
					msb.setMerStatus("提示级");
				}else if(Constance.Null2EmptyTrim(msb.getMerStatus()).equals("A2")){
					msb.setMerStatus("关注级");
				}else if(Constance.Null2EmptyTrim(msb.getMerStatus()).equals("A3")){
					msb.setMerStatus("预警级");
				}else if(Constance.Null2EmptyTrim(msb.getMerStatus()).equals("A4")){
					msb.setMerStatus("拒绝级");
				}
				msList.add(msb);
			}
		}
		return msList;	
	}

	public String getExcelName() {
		String excelName="商户详情"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_MERINFO_BATCHEXPORT, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_MERINFO_BATCHEXPORT);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}


	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

	

	public MerinfoSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(MerinfoSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public List<OrgBean> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<OrgBean> orgList) {
		this.orgList = orgList;
	}

	

}
